package com.piik.mall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.piik.common.constant.ProductConstant;
import com.piik.common.dto.MemberPrice;
import com.piik.common.dto.SkuHasStockDTO;
import com.piik.common.dto.SkuReductionDTO;
import com.piik.common.dto.SpuBoundDTO;
import com.piik.common.dto.es.SkuESModel;
import com.piik.common.utils.R;
import com.piik.mall.product.entity.*;
import com.piik.mall.product.feign.CouponFeignService;
import com.piik.mall.product.feign.SearchFeignService;
import com.piik.mall.product.feign.WareFeignService;
import com.piik.mall.product.service.*;
import com.piik.mall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piik.common.utils.PageUtils;
import com.piik.common.utils.Query;

import com.piik.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;


    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;
    
    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void save(SpuInfoVO spuInfoVO) {

        // 1. 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(0);
        this.save(spuInfoEntity);

        // 2. 保存spu的详情信息 pms_spu_info_desc
        List<String> decript = spuInfoVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 3.保存图片集信息 pms_spu_images
        List<String> images = spuInfoVO.getImages();
        if (images != null && images.size() > 0) {
            List<SpuImagesEntity> spuImagesEntities = images.stream().map(item -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(item);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntities);
        }

        // 4.保存规格参数信息 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        if (baseAttrs != null && baseAttrs.size() > 0) {
            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrId(attr.getAttrId());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());
                productAttrValueEntity.setQuickShow(attr.getShowDesc());
                AttrEntity attrEntity = attrService.getById(attr.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntities);
        }

        // 5.保存当前spu对应所有的sku信息
        List<Skus> skus = spuInfoVO.getSkus();
        if (skus != null && skus.size() > 0) {
           skus.forEach((item) -> {
                // 5.1 保存sku基本信息 pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0l);
                List<Images> itemImages = item.getImages();
                String defaultImage = "";
                for (Images image : itemImages) {
                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.save(skuInfoEntity);


                // 5.2 保存sku图片信息 pms_sku_images
               List<Images> imagesList = item.getImages();
               List<SkuImagesEntity> skuImagesEntities = imagesList.stream().map(image -> {
                   SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                   skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                   skuImagesEntity.setImgUrl(image.getImgUrl());
                   skuImagesEntity.setDefaultImg(image.getDefaultImg());
                   return skuImagesEntity;
               }).filter(img-> {
                   return img.getDefaultImg() == 1;// TODO 为空的图片不需要保存
               }).collect(Collectors.toList());
               skuImagesService.saveBatch(skuImagesEntities);

               // 5.3 保存满减信息,折扣,会员价 mall-sms：sms_sku_full_reduction,sms_sku_ladder,sms_member_price
               SkuReductionDTO skuReductionDTO = new SkuReductionDTO();
               BeanUtils.copyProperties(item,skuReductionDTO);
               skuReductionDTO.setSkuId(skuInfoEntity.getSkuId());
               // 设置会员价
               if(item.getMemberPrice() != null && item.getMemberPrice().size()>0){
                   List<MemberPrice> memberPrices = item.getMemberPrice().stream().map(mPrice -> {
                       MemberPrice memberPrice = new MemberPrice();
                       BeanUtils.copyProperties(mPrice, memberPrice);
                       return memberPrice;
                   }).collect(Collectors.toList());
                   skuReductionDTO.setMemberPrice(memberPrices);
               }
               R r = couponFeignService.saveFullReductionInfo(skuReductionDTO);
               if(r.getCode()!=0){
                   log.error("调用Coupon服务处理满减、折扣、会员价操作失败...");
               }

               // 5.4 保存sku的销售信息 pms_sku_sale_attr_value
               List<Attr> attr = item.getAttr();
               List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(saleAttr -> {
                   SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                   BeanUtils.copyProperties(saleAttr, skuSaleAttrValueEntity);
                   skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                   return skuSaleAttrValueEntity;
               }).collect(Collectors.toList());
               skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            });
        }
        // 6. 保存spu积分信息 sms_spu_bounds
        Bounds bounds = spuInfoVO.getBounds();
        SpuBoundDTO spuBoundDTO = new SpuBoundDTO();
        BeanUtils.copyProperties(bounds,spuBoundDTO);
        spuBoundDTO.setSpuId(spuInfoEntity.getId());
        R r= couponFeignService.saveSpuBound(spuBoundDTO);
        if(r.getCode()!=0){
          log.error("调用Coupon服务存储积分信息操作失败");
        }
    }

    /**
     * spu检索信息
     * 分页查询
     * 品牌、分类，状态，关键词查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        // 关键词
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w->{
               w.eq("id",key).or().like("spu_name",key).or().like("spu_description",key);
            });
        }
        // 状态
        String publishStatus = (String) params.get("status");
        if(!StringUtils.isEmpty(publishStatus)){
          wrapper.eq("publish_status",publishStatus);
        }

        // 分类
        String  catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        // 品牌
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        List<SpuInfoVO> spuInfoVOList = page.getRecords().stream().map(spu -> {
            Long catalogId1 = spu.getCatalogId();
            CategoryEntity categoryEntity = categoryService.getById(catalogId1);
            Long brandId1 = spu.getBrandId();
            BrandEntity brandEntity = brandService.getById(brandId1);
            SpuInfoVO vo = new SpuInfoVO();
            BeanUtils.copyProperties(spu, vo);
            vo.setCatalogName(categoryEntity.getName());
            vo.setBrandName(brandEntity.getName());
            return vo;
        }).collect(Collectors.toList());
        IPage<SpuInfoVO> ipage = new Page<>();
        ipage.setRecords(spuInfoVOList);
        ipage.setPages(page.getPages());
        ipage.setCurrent(page.getCurrent());
        return new PageUtils(ipage);
    }


    /**
     * 实现商品上架--》商品相关数据存储到ElasticSearch中
     * 1.根据SpuID查询出相关的信息
     *   封装到对应的对象中
     * 2.将封装的数据存储到ElasticSearch中--》调用mall-search的远程接口
     * 3.更新SpuID对应的状态--》上架
     *
     * @param spuId
     */
    @Transactional
    @Override
    public void up(Long spuId) {
        // 1.根据spuId查询相关的信息 封装到SkuESModel对象中
        ArrayList<SkuESModel> skuESModels = new ArrayList<>();

        // 根据spuId 查询对应的sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 对应的规格参数,根据spuId来查规格参数信息
        List<SkuESModel.Attrs> attrsModel=getAttrsModel(spuId);

        // 需要根据所有的skuId获取对应的库存信息---》远程调用
        List<Long> skuIds = skus.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());

        Map<Long, Boolean> skusHasStockMap = getSkusHasStock(skuIds);
        // 2.远程调用mall-search的服务，将SukESModel中的数据存储到ES中
        List<SkuESModel> esModels = skus.stream().map(item -> {
            SkuESModel model = new SkuESModel();
            // 先实现属性的复制
            BeanUtils.copyProperties(item, model);
            model.setSubTitle(item.getSkuTitle());
            model.setSkuPrice(item.getPrice());
            model.setSkuImg(item.getSkuDefaultImg());

            // hasStock 是否有库存 --》 库存系统查询  一次远程调用获取所有的skuId对应的库存信息
            if (skusHasStockMap != null && skusHasStockMap.size() > 0) {
                model.setHasStock(skusHasStockMap.get(item.getSkuId()));
            } else {
                model.setHasStock(true);
            }
            // hotScore 热度分 --> 默认给0即可
            model.setHotScore(0l);
            // 品牌名称,图片
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            model.setBrandName(brandEntity.getName());
            model.setBrandImg(brandEntity.getLogo());
            //类型名称
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            model.setCatalogName(categoryEntity.getName());

            // 需要存储的规格数据
            model.setAttrs(attrsModel);
            return model;
        }).collect(Collectors.toList());

        // 将SkuESModel中的数据存储到ES中
        R r=null;
        if(esModels != null && esModels.size()>0){
            r = searchFeignService.productStatusUp(esModels);
        }
        // 3.更新SPUID对应的状态
        // 根据对应的状态更新商品的状态
        log.info("----->ES操作完成：{}" ,r.getCode());
        System.out.println("-------------->"+r.getCode());
        if(r.getCode()==0){
            // 远程调用成功  更新商品的状态为 上架
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            log.info("----->远程调用ES失败：{}" ,r.getCode());
        }
    }

   /**
     * 根据skuIds获取对应的库存状态
     * @param skuIds
     * @return
     */
    private Map<Long, Boolean>  getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockDTO> skusHasStock = wareFeignService.getSkusHasStock(skuIds);
        try {
            Map<Long, Boolean> map = skusHasStock.stream().
                    collect(Collectors.toMap(SkuHasStockDTO::getSkuId, item -> item.getHasStock()));
            return map;
        }catch (Exception e){e.printStackTrace();}
        return null;

    }

    /**
     * 根据spuId获取对应的规格参数
     * @param spuId
     * @return
     */
    private List<SkuESModel.Attrs> getAttrsModel(Long spuId) {

        // 1. product_attr_value 存储了对应的spu相关的所有的规格参数
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.
                list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = null;
        if(baseAttrs !=null && baseAttrs.size()>0){
            // 2. attr search_type 决定该属性是否支持检索
            attrIds = baseAttrs.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
        }
        // 查询出所有的可以检索的对应的规格参数编号
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        // 根据 检查条件searchAttrIds 过滤baseAttrs信息
        List<SkuESModel.Attrs> attrsModel = null ;
        if(searchAttrIds !=null && searchAttrIds.size()>0){
             attrsModel = baseAttrs.stream().filter(item -> {
                return searchAttrIds.contains(item.getAttrId());
            }).map(item -> {
                SkuESModel.Attrs attrs = new SkuESModel.Attrs();
                BeanUtils.copyProperties(item, attrs);
                return attrs;
            }).collect(Collectors.toList());
        }
      return attrsModel;
    }

}